package phapp.springSecurity;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

/**
 * 决策类（决定用户是否用权限访问所请求的资源）
 * 
 */
public class MyAccessDecisionManager implements AccessDecisionManager
{

   /*
    * (non-Javadoc)
    * 
    * @see org.springframework.security.access.AccessDecisionManager#decide(org.
    * springframework.security.core.Authentication 用户所拥有的所有权限, java.lang.Object
    * 请求的资源, java.util.Collection 访问所请求资源所需的权限信息)
    */
   public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException
   {
      String NeedPermission = "";
      ConfigAttribute configAttribute = null;
      
      //不需要任何权限即可访问
      if (configAttributes == null)   return;

      Iterator<ConfigAttribute> iterator = configAttributes.iterator();
      while (iterator.hasNext())
      {
         configAttribute = iterator.next();
         NeedPermission = ((SecurityConfig) configAttribute).getAttribute();
         // Collection<GrantedAuthority> gaCollection = authentication.getAuthorities();
         // System.out.println("\n\n\nauthentication.getAuthorities() - " + authentication.getAuthorities().toString() + "\n\n\n");

         Collection<? extends GrantedAuthority> gaCollection = authentication.getAuthorities();
         if (gaCollection != null)
         {
            for (GrantedAuthority ga : gaCollection)
            {
               if (NeedPermission.equals(ga.getAuthority()))
                  return;
            }
         }
         configAttribute = null;
      }
      
      throw new AccessDeniedException("您无权访问该资源,请与管理员联系!");
   }

   public boolean supports(ConfigAttribute attribute)
   {
      return true;
   }

   public boolean supports(Class<?> clazz)
   {
      return true;
   }
   

}
